package com.megvii.koala.tv.fragment;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.RelativeLayout;

import com.megvii.corelib.components.BaseNetworkErrorView;
import com.megvii.koala.base.KoalaPresenter;
import com.megvii.koala.tv.R;
import com.megvii.koala.tv.presenter.BoxSettingPresenter;

import java.util.List;

import butterknife.Bind;
import butterknife.OnClick;
import butterknife.OnItemClick;

/**
 * Created by linyue on 16/1/22.
 */
public class BoxSettingFragment extends BaseFragment
{
    protected View rootView;

    @Bind(R.id.box_root)
    protected RelativeLayout rootRelativeLayout;

    @Bind(R.id.box_list)
    protected ListView listView;

    private ArrayAdapter<String> adapter;

    private BoxSettingListener listener;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState)
    {
        if (rootView == null)
        {
            rootView = inflater.inflate(R.layout.box_layout, container, false);
        }
        return rootView;
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState)
    {
        super.onViewCreated(view, savedInstanceState);
        adapter = new ArrayAdapter<>(this.getActivity(), R.layout.box_item, R.id.box_item_text);
        listView.setAdapter(adapter);
    }

    public void updateBoxes(List<String> addresses)
    {
        adapter.clear();
        if (addresses != null)
        {
            for (String address : addresses)
            {
                adapter.add(address);
            }
        }
    }

    public void addBox(String address)
    {
        adapter.add(address);
    }

    public RelativeLayout getRootRelativeLayout()
    {
        return rootRelativeLayout;
    }

    @OnItemClick(R.id.box_list)
    public void onItemClick(AdapterView<?> parent, View view, int position, long id)
    {
        if (listener != null)
        {
            listener.onChooseItem(position);
        }
    }

    @OnClick(R.id.box_manually_add)
    public void onClick(View view)
    {
        if (listener != null)
        {
            listener.onClickAddBoxButton();
        }
    }

    @Override
    public BaseFragmentListener getBaseFragmentListener()
    {
        return listener;
    }

    @Override
    public Class<? extends KoalaPresenter> getPresenterClass()
    {
        return BoxSettingPresenter.class;
    }

    @Override
    public BaseNetworkErrorView getNetworkErrorView()
    {
        return null;
    }

    public void setListener(BoxSettingListener listener)
    {
        this.listener = listener;
    }

    public interface BoxSettingListener extends BaseFragmentListener
    {
        public void onChooseItem(int position);

        public void onClickAddBoxButton();
    }
}
